package com.cm.tianwt.socks.test.http;

import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Base64;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

public class HttpTester {
	
	public static void main(String[] args) throws MalformedURLException {
		
		InetSocketAddress socksAddress = new InetSocketAddress("127.0.0.1", 8888);
		Proxy proxy = new Proxy(Type.HTTP, socksAddress);
		
		Authenticator.setDefault(new MyAuthenticator("admin", "nimda"));
		
		 try {
			 SSLContext sslcontext = SSLContext.getInstance("SSL","SunJSSE");
			 sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
			 HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
			        public boolean verify(String s, SSLSession sslsession) {
			            System.out.println("WARNING: Hostname is not matched for cert.");
			            return true;
			        }
			   };
			   HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
			   HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
			   
			//   testGet(proxy,"http://test.m.ncfimg.com");
			   testGet(proxy,"https://www.baidu.com");
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	
		
	}

	private static void testGet(Proxy proxy,String url) {
		try {
			
			
			 String headerkey = "Proxy-Authorization";  
             String headerValue = "Basic "+Base64.getEncoder().encodeToString("admin:nimda".getBytes()); //甯愬彿瀵嗙爜鐢�:闅斿紑锛宐ase64鍔犲瘑鏂瑰紡  
			
			HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(proxy);
			
			httpConnection.setRequestProperty(headerkey, headerValue);  
			httpConnection.connect();
			
			InputStream inputStream = httpConnection.getInputStream();
			int len = -1;
			byte[] buf = new byte[1024];
			
			while ((len=inputStream.read(buf, 0, buf.length))!=-1) {
				System.out.println(new String(buf, 0, len));
			}
			
			inputStream.close();
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
